package com.lc.zpyh.ui.activity.supermarket;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.zpyh.R;
import com.lc.zpyh.adapter.ImageShopDetailsAdapter;
import com.lc.zpyh.adapter.MultipleTypesAdapter;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.AddCartApi;
import com.lc.zpyh.http.request.CancelFavoriteApi;
import com.lc.zpyh.http.request.CondimentsQueryApi;
import com.lc.zpyh.http.request.DeleteByIdsApi;
import com.lc.zpyh.http.request.FavoritesApi;
import com.lc.zpyh.http.request.IsfavoritesApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.request.SelectByCommodityIdApi;
import com.lc.zpyh.http.request.SelectMyCartApi;
import com.lc.zpyh.http.request.SelectToBeConfirmedApi;
import com.lc.zpyh.http.request.SetByCommodityIdApi;
import com.lc.zpyh.http.request.ShareSelectByTypeApi;
import com.lc.zpyh.http.request.queatAllApi;
import com.lc.zpyh.http.response.CondimentsQueryBean;
import com.lc.zpyh.http.response.IsfavoritesBean;
import com.lc.zpyh.http.response.SelectByCommodityIdBean;
import com.lc.zpyh.http.response.SelectMerChantEvaluationBean;
import com.lc.zpyh.http.response.SelectMyCartBean;
import com.lc.zpyh.http.response.SelectToBeConfirmedBean;
import com.lc.zpyh.http.response.SetByCommodityIdBean;
import com.lc.zpyh.http.response.ShareSelectByTypeBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.sqlite.BrowseDao;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.CourseUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.view.GoodsAttrDialog;
import com.lc.zpyh.view.LooKVideoDialog;
import com.lc.zpyh.view.ShoppingCartDialog;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDetailsActivity extends AppActivity implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.ll_banner)
    LinearLayout llBanner;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_yueshou)
    TextView tvYueshou;
    @BindView(R.id.tv_gouwuche)
    TextView tvGouwuche;
    @BindView(R.id.rg_page)
    RadioGroup rgPage;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.rl_web)
    RelativeLayout rlWeb;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl_pingjia)
    RelativeLayout rlPingjia;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedscrollview;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.icon_shoucang)
    ImageView icon_shoucang;
    @BindView(R.id.tv_tupian)
    TextView tvTupian;
    @BindView(R.id.tv_shipin)
    TextView tvShipin;
    @BindView(R.id.tv_xiadan)
    TextView tvXiadan;
    @BindView(R.id.rv_details)
    RecyclerView rvDetails;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    private BaseQuickAdapter<SelectMerChantEvaluationBean.ListBean, BaseViewHolder> pingjiaadapter;

    private RadioButton radioButton1;
    private GoodsAttrDialog goodsAttrDialog;
    List<String> orderList = new ArrayList<>();
    List<SelectMyCartBean.ListBean.CartsBean> dataBeanList = new ArrayList<>();
    private BrowseDao browseDao;
    private String newsTextSrart = "<html>" +
            "<head>" +
            "<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'>" +
            "</head>" +
            "<body>";

    private String newsTextEnd = "<style type=\"text/css\"> img {" +
            "width: 100% !important;" +
            "height:auto !important;" +
            "}" +
            "</style>" +
            "</body></html>";
    //    商品id
    private String commodityId;
    //    banner 集合
    private List<String> imageList = new ArrayList<>();
    List<CondimentsQueryBean.ListBean> dataxiaoliaoList = new ArrayList<>();
    private int mPosition = 0;
    private int page;
    private String merchantid;
    private String shopimg;
    private String shopname;
    private String commodityName;
    private String date;
    private ShoppingCartDialog shoppingCartDialog;
    private String price;
    private boolean istrue;
    private int intcount = 0;
    private BaseQuickAdapter<String, BaseViewHolder> imgadapter;
    private String video;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopdetails;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        tvTupian.setText("图片");
        tvShipin.setText("视频");
        commodityId = getIntent().getStringExtra("commodityId");
        merchantid = getIntent().getStringExtra("merchantid");
        shopimg = getIntent().getStringExtra("img");
        shopname = getIntent().getStringExtra("shopname");
        commodityName = getIntent().getStringExtra("commodityname");
        price = getIntent().getStringExtra("price");
        date = getDate(Calendar.getInstance().getTimeInMillis() / 1000);
        browseDao = new BrowseDao(this);
       if ( !browseDao.isHasRecord(commodityId)){
           browseDao.add(commodityName, shopname, shopimg, date, merchantid, commodityId);
       }

        rgPage.setOnCheckedChangeListener(this);
        radioButton1 = findViewById(R.id.rb_diancan);
        radioButton1.setChecked(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);//设置webview推荐使用的窗口
        webSettings.setLoadWithOverviewMode(true);//设置webview加载的页面的模式
        webSettings.setDisplayZoomControls(false);//隐藏webview缩放按钮
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {

                LogUtil.i("webview加载结束");
            }
        });
//        webView.loadDataWithBaseURL(null, newsTextSrart + content + newsTextEnd
//                , "text/html", "UTF-8", null);

        xiangqing();
        pingjia(page);
        selectMyCart();
        isfavorites();

        imgadapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_shop_img, imageList) {
            @Override
            protected void convert(@NotNull BaseViewHolder holder, String s) {
                GlideApp.with(ShopDetailsActivity.this).load(IntentKey.ORDER_IMAGE + s).apply(new RequestOptions().placeholder(R.mipmap.image11).error(R.mipmap.image11)).into(((ImageView) holder.getView(R.id.img)));
            }
        };
        rvDetails.setAdapter(imgadapter);
    }

    /**
     * 此商品是否收藏
     */
    private void isfavorites() {
        EasyHttp.post(this)
                .api(new IsfavoritesApi().setUserId(SPUtil.get(this, IntentKey.USERID, "")).setCommodityId(commodityId)).request(new HttpCallback<IsfavoritesBean>(this) {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSucceed(IsfavoritesBean data) {
                if (data.getCode() == 0) {
                    istrue = data.isList();
                    if (data.isList()) {
                        icon_shoucang.setImageResource(R.mipmap.collect_true);
                    } else {
                        icon_shoucang.setImageResource(R.mipmap.collect_false);
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void xiangqing() {
        imageList.clear();
        EasyHttp.post(this)
                .api(new SelectByCommodityIdApi().setId(commodityId).setUserId(SPUtil.get(this, IntentKey.USERID, ""))).request(new HttpCallback<SelectByCommodityIdBean>(this) {

            @Override
            public void onSucceed(SelectByCommodityIdBean data) {
                if (data.getCode() == 0) {
//                    if (CourseUtils.isNotNullOrEmpty(data.getList().getVideo())){
//                        imageList.add(new BannerDataBean(data.getList().getVideo(), "", 2))
//                        ;
//                    }
                    if (data.getList().getDetails().isEmpty()) {
                        rvDetails.setVisibility(View.VISIBLE);
                    }
                    if (!data.getList().getImg().isEmpty()){
                        imageList.add(data.getList().getImg());
                    }
                    if (data.getList().getImgs() != null && data.getList().getImgs().size() > 0) {

                        if (!data.getList().getImgs().get(0).getCommodityImg1().isEmpty()) {
                            imageList.add(data.getList().getImgs().get(0).getCommodityImg1());
                        }
                        if (!data.getList().getImgs().get(0).getCommodityImg2().isEmpty()) {
                            imageList.add(data.getList().getImgs().get(0).getCommodityImg2());
                        }
                        if (!data.getList().getImgs().get(0).getCommodityImg3().isEmpty()) {
                            imageList.add(data.getList().getImgs().get(0).getCommodityImg3());
                        }
                        if (!data.getList().getImgs().get(0).getCommodityImg4().isEmpty()) {
                            imageList.add(data.getList().getImgs().get(0).getCommodityImg4());
                        }
                        if (!data.getList().getImgs().get(0).getCommodityImg5().isEmpty()) {
                            imageList.add(data.getList().getImgs().get(0).getCommodityImg5());
                        }

                        imgadapter.setNewData(imageList);
                    }
                    if (data.getList().getStatus() == 1) {
                        tvXiadan.setText("商家打样");
                        tvXiadan.setEnabled(false);
                    } else {
                        tvXiadan.setText("下单");
                        tvXiadan.setEnabled(true);
                    }
                    banner.setAdapter(new ImageShopDetailsAdapter(getContext(), imageList)).setIndicator(new CircleIndicator(getContext())).setIndicatorGravity(IndicatorConfig.Direction.CENTER).setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(Object data, int position) {
//                            ToastUtils.show(position);
                        }
                    });
//
                    if (data.getList().getVideo() != null) {
                        if (data.getList().getVideo().contains("http")) {
                            video = data.getList().getVideo();
                        } else {
                            video = IntentKey.CAR_IMAGE + data.getList().getVideo();
                        }
                    }
                    tvGoodsName.setText(data.getList().getCommodityName());
                    if (data.getList().getPrePrice() != null) {
                        tvMoney.setText("￥" + BigDecimalUtils.div(data.getList().getPrePrice() + "", "100", 2));
                    } else {
                        if (data.getList().getPrice() != null) {
                            tvMoney.setText("￥" + BigDecimalUtils.div(data.getList().getPrice() + "", "100", 2));
                        }
                    }


                    tvYueshou.setText("月售" + data.getList().getSales() + "份");
                }


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void pingjia(int page) {
        EasyHttp.post(this)
                .api(new queatAllApi().setCommodityId(commodityId).setPage(page + "")).request(new HttpCallback<SelectMerChantEvaluationBean>(this) {

            @Override
            public void onSucceed(SelectMerChantEvaluationBean data) {
                if (data.getCode() == 0) {

                    pingjiaadapter = new BaseQuickAdapter<SelectMerChantEvaluationBean.ListBean, BaseViewHolder>
                            (R.layout.item_myevaluate, data.getList()) {

                        @Override
                        protected void convert(BaseViewHolder viewHolder, SelectMerChantEvaluationBean.ListBean commentOrderBean) {


                            viewHolder.setText(R.id.tv_shop_name, commentOrderBean.getUserName());
                            viewHolder.setText(R.id.tv_date, commentOrderBean.getCommentTime());
                            if (commentOrderBean.getNameOne()==null){
                                viewHolder.setText(R.id.tv_specs, "规格:默认" );
                            }else {
                                if (commentOrderBean.getNameTwo()==null){
                                    viewHolder.setText(R.id.tv_specs, "规格:"+commentOrderBean.getNameOne() );
                                }else {
                                    viewHolder.setText(R.id.tv_specs, "规格:"+commentOrderBean.getNameOne()  +"、" + commentOrderBean.getNameTwo());

                                }
                            }

                            GlideApp.with(getContext()).load(IntentKey.CAR_IMAGE+commentOrderBean.getUserImg()).into(((ImageView) viewHolder.getView(R.id.img_head)));
                            int starSpeed = commentOrderBean.getDeliverySpeed();
                            viewHolder.setImageResource(R.id.iv_speed_start_1, starSpeed >= 2 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_speed_start_2, starSpeed >= 4 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_speed_start_3, starSpeed >= 6 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_speed_start_4, starSpeed >= 8 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_speed_start_5, starSpeed >= 10 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);

                            int starhealth = commentOrderBean.getHealthSituation();
                            viewHolder.setImageResource(R.id.iv_hygiene_start_1, starhealth >= 2 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_hygiene_start_2, starhealth >= 4 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_hygiene_start_3, starhealth >= 6 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_hygiene_start_4, starhealth >= 8 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_hygiene_start_5, starhealth >= 10 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            int starpreservation = commentOrderBean.getHeatPreservation();
                            viewHolder.setImageResource(R.id.iv_effect_start_1, starpreservation >= 2 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_effect_start_2, starpreservation >= 4 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_effect_start_3, starpreservation >= 6 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_effect_start_4, starpreservation >= 8 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                            viewHolder.setImageResource(R.id.iv_effect_start_5, starpreservation >= 10 ? R.mipmap.ic_comment_full : R.mipmap.ic_comment_empty);
                        }
                    };


                    recyclerView.setAdapter(pingjiaadapter);
                }

            }

            @Override
            public void onFail(Exception e) {
//                super.onFail(e);

            }
        });

    }

    private void stopVideo(int position) {
        int type = banner.getAdapter().getItemViewType(position);
        if (type == 2) {
//            SuperPlayerModel model = new SuperPlayerModel();
//
//            if (CourseUtils.isNotNullOrEmpty(resultBean.getVideo())){
//                model.url=resultBean.getVideo();
//            }
//            if (mIsPlaying){
//                MultipleTypesAdapter.VideoHolder holder = (MultipleTypesAdapter.VideoHolder) ((MultipleTypesAdapter) banner.getAdapter()).getVHMap().get(position);
//                holder.player.playWithModel(model, (int) mCurrentTime);
//                mIsPlaying = false;
//            }


        } else {
            RecyclerView.ViewHolder holder = ((MultipleTypesAdapter) banner.getAdapter()).getVHMap().get(0);
            if (holder instanceof MultipleTypesAdapter.VideoHolder) {
                MultipleTypesAdapter.VideoHolder videoHolder = (MultipleTypesAdapter.VideoHolder) holder;
//                if (videoHolder.player.getPlayState() != SuperPlayerConst.PLAYSTATE_PAUSE){
//                    mIsPlaying = true;
//                    videoHolder.player.onPause();
//                    mCurrentTime = videoHolder.player.getTCControllerWindow().getmProgress();
//                }
            }


        }


//
//
//
//
//
//
//
//
//
//
//
//        if (player == null) {
//            Log.e("@@@@@", "stopVideo: "+"11111111111111111111" );
//            Log.e("@@@@@", "getItemViewType: "+banner.getAdapter().getViewHolder().getItemViewType());
//            if (banner.getAdapter().getItemViewType(position) == 2) {
//                MultipleTypesAdapter.VideoHolder holder = (MultipleTypesAdapter.VideoHolder) ((MultipleTypesAdapter) banner.getAdapter()).getVHMap().get(position);
//                Log.e("@@@@@", "stopVideo: "+"2222222222222222222" );
//                Log.e("@@@@@", "stopVideo: "+holder.player+"" );
//                player = holder.player;
//                mCurrentTime = player.getTCControllerWindow().getmProgress();
//                Log.e("@@@@@@1", "stopVideo: "+player.getTCControllerWindow().getmProgress());
//                if (position != 0) {
//                    Log.e("@@@@@", "stopVideo: "+"3333333333333333333333" );
//                    player.playWithModel(model,(int) player.getTCControllerWindow().getmProgress());
//                    Log.e("@@@@@@2", "stopVideo: "+player.getTCControllerWindow().getmProgress());
//                }
//            }
//
//        }
//        else {
//            if (position != 0) {
//                Log.e("@@@@@", "stopVideo: "+"4444444444444444444444" );
//                Log.e("@@@@@@3", "stopVideo: "+player.getTCControllerWindow().getmProgress());
////                player.playWithModel(model,(int) player.getTCControllerWindow().getmProgress());
////
//            } else {
//                player.playWithModel(model,(int) player.getTCControllerWindow().getmProgress());
//            }
//        }
    }

    private void shareSelectByType() {
        EasyHttp.post(this)
                .api(new ShareSelectByTypeApi().setType("商品").setId(commodityId)).request(new HttpCallback<ShareSelectByTypeBean>(this) {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSucceed(ShareSelectByTypeBean data) {
                if (data.getCode() == 0) {
                    getSystemService(ClipboardManager.class).setPrimaryClip(ClipData.newPlainText("url", data.getList().getContent()));
                    ToastUtils.show(R.string.share_platform_copy_hint);

                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private String getDate(long milliSeconds) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // Create a calendar object that will convert the date and time value in
        // milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds * 1000L);
        return formatter.format(calendar.getTime());
    }

    @OnClick({R.id.image_back, R.id.icon_shoucang, R.id.rl_fenxiang, R.id.tv_tupian, R.id.tv_shipin, R.id.tv_gouwuche, R.id.rl_bottom, R.id.tv_xiadan,R.id.rl_shopping_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.icon_shoucang:
                if (istrue) {
                    cancelFavorite();
                } else {
                    favorites();
                }
                break;
            case R.id.rl_fenxiang:
                shareSelectByType();
                break;
            case R.id.tv_tupian:
                break;
            case R.id.tv_shipin:
                if (video == null || video.isEmpty() || video.equals(IntentKey.CAR_IMAGE)) {
                    toast("暂无可播放视频");
                    return;
                }
                LooKVideoDialog LooKVideoDialog = new LooKVideoDialog(this, video, tvGoodsName.getText().toString());
                LooKVideoDialog.show();
                break;
            case R.id.tv_xiadan:
                selectToBeConfirmed();
                break;
            case R.id.rl_shopping_cart:
            case R.id.tv_gouwuche:
                intcount++;
//
                isAttr(commodityId, "1", "", price, commodityName, "");
//

//
                break;

            case R.id.rl_bottom:
                shoppingCartDialog = new ShoppingCartDialog(ShopDetailsActivity.this, merchantid, dataBeanList);
                shoppingCartDialog.show();
                shoppingCartDialog.setOnGoodsOrderListener(new ShoppingCartDialog.OnGoodsOrderListener() {
                    @Override
                    public void onDismiss(String[] specification, String num, String shopPrice, String intPrice, String vipPrice, String integralPrice, String deductionIntegral) {

                    }

                    @Override
                    public void onAddShoppingCart(String id, String count, String prePrice, String price, String condimentsId, String cardId,String cartcount) {
                        intcount = Integer.parseInt(count);
//
                            addShopCart(id, count, prePrice, price, condimentsId);
//
                    }

                    @Override
                    public void onSubShoppingCart() {
                        selectMyCart();
                    }

                    @Override
                    public void OrderCom(List<String> orderList) {
                        selectToBeConfirmed();
                    }


                });

                break;
        }
    }

    /**
     * 取消收藏
     */
    private void cancelFavorite() {
        EasyHttp.post(this)
                .api(new CancelFavoriteApi().setUserId(SPUtil.get(this, IntentKey.USERID, "")).setCommodityId(commodityId)).request(new HttpCallback<IsfavoritesBean>(this) {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSucceed(IsfavoritesBean data) {
                if (data.getCode() == 0) {
                    istrue = false;
                    if (istrue) {
                        icon_shoucang.setImageResource(R.mipmap.collect_true);
                    } else {
                        toast("已取消收藏");
                        icon_shoucang.setImageResource(R.mipmap.collect_false);
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 收藏
     */
    private void favorites() {
        EasyHttp.post(this)
                .api(new FavoritesApi().setUserId(SPUtil.get(this, IntentKey.USERID, "")).setCommodityId(commodityId)).request(new HttpCallback<IsfavoritesBean>(this) {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSucceed(IsfavoritesBean data) {
                if (data.getCode() == 0) {
                    istrue = data.isList();
                    if (data.isList()) {
                        icon_shoucang.setImageResource(R.mipmap.collect_true);
                        toast("收藏成功");
                    } else {
                        icon_shoucang.setImageResource(R.mipmap.collect_false);
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 购物车数据
     */
    private void selectMyCart() {
        EasyHttp.post(this)
                .api(new SelectMyCartApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setPageNum("1").setPageSize("10").setMerchantid(merchantid).setSchoolid(SPUtil.get(this, IntentKey.ADDRESSID, ""))).request(new HttpCallback<SelectMyCartBean>(this) {

            @Override
            public void onSucceed(SelectMyCartBean data) {
                if (data.getCode() == 0) {
                    if (data.getList().size() > 0) {
                        tvXiadan.setVisibility(View.VISIBLE);
                        String totalNum = "0";
                        String totalPrice = "0";
                        for (int i = 0; i < data.getList().get(0).getCarts().size(); i++) {
                            if (String.valueOf(data.getList().get(0).getCarts().get(i).getCommodityId()).equals(commodityId)) {
                                intcount = data.getList().get(0).getCarts().get(i).getCount();
                            }
                            if (data.getList().get(0).getCarts().get(i).getGgzzt()==null){
                                data.getList().get(0).getCarts().get(i).setGgzzt(0);
                            }
                            if (data.getList().get(0).getCarts().get(i).getSpzt()==0&&data.getList().get(0).getCarts().get(i).getGgzzt()==0) {
                                totalNum = BigDecimalUtils.add(totalNum, data.getList().get(0).getCarts().get(i).getCount() + "", 0);
                                totalPrice = BigDecimalUtils.add(totalPrice, BigDecimalUtils.mul(BigDecimalUtils.div(data.getList().get(0).getCarts().get(i).getPrice() + "", "100", 2), data.getList().get(0).getCarts().get(i).getCount() + "", 2), 2);
                            }
                        }

                        tvTotalMoney.setText(totalPrice);

                        tvNum.setText("已选" + totalNum + "件");
                        dataBeanList.clear();
                        dataBeanList.addAll(data.getList().get(0).getCarts());
                        if (shoppingCartDialog != null) {
                            shoppingCartDialog.setDataList(dataBeanList);
                        }
                    } else {
                        tvXiadan.setVisibility(View.INVISIBLE);
                        tvTotalMoney.setText("0.00");
                        tvNum.setText("已选" + "0" + "件");
                        dataBeanList.clear();
                        if (shoppingCartDialog != null) {
                            shoppingCartDialog.setDataList(dataBeanList);
                        }
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 下单
     */
    private void selectToBeConfirmed() {
        orderList.clear();
        if (dataBeanList.size() != 0) {
            for (int i = 0; i < dataBeanList.size(); i++) {
                orderList.add(dataBeanList.get(i).getCartId() + "");
            }
        } else {
            toast("购物车还空着");
            return;
        }
        EasyHttp.post(this)
                .api(new SelectToBeConfirmedApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setSchoolId(SPUtil.get(this, IntentKey.ADDRESSID, "")).setCartIds(CourseUtils.listToString1(orderList))).request(new HttpCallback<SelectToBeConfirmedBean>(this) {

            @Override
            public void onSucceed(SelectToBeConfirmedBean data) {
                if (data.getCode() == 0) {
                    startActivity(new Intent(ShopDetailsActivity.this, ConfirmOrderActivity.class).putExtra("orderList", data.getList()).putExtra("cartIds", CourseUtils.listToString1(orderList)));
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * // 点击加号 判断是否有规格
     *
     * @param id
     */
    private void isAttr(String id, String count, String prePrice, String price, String commodityName, String condimentsId) {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new SetByCommodityIdApi().setId(id)).request(new OnHttpListener<SetByCommodityIdBean>() {

            @Override
            public void onSucceed(SetByCommodityIdBean data) {
                if (data.getCode() == 0) {

                    shangjiaxiaoliao(data.getList().getSpecificationCategoryNameOne(), data.getList().getSpecificationCategoryListOne(), data.getList().getSpecificationCategoryNameTwo(), data.getList().getSpecificationCategoryListTwo(), id, commodityName, count,price,condimentsId);
                }
            }

            @Override
            public void onFail(Exception e) {


            }
        });
    }

    /**
     * 商家是否有小料
     */
    private void shangjiaxiaoliao(String name1, List<SetByCommodityIdBean.ListBean.SpecificationCategoryListOneBean> listone, String name2, List<SetByCommodityIdBean.ListBean.SpecificationCategoryListTwoBean> listtwo, String id, String commodityName, String count,String price,String condimentsId) {
        EasyHttp.post(this)
                .api(new CondimentsQueryApi().setCommodityId(id)).request(new HttpCallback<CondimentsQueryBean>(this) {

            @Override
            public void onSucceed(CondimentsQueryBean data) {
                if (data.getCode() == 0) {
                    dataxiaoliaoList.clear();
                    dataxiaoliaoList.addAll(data.getList());
                    if (listone != null || listtwo != null || data.getList().size() > 0) {
                        goodsAttrDialog = new GoodsAttrDialog(ShopDetailsActivity.this, name1, listone, name2, listtwo, dataxiaoliaoList, id, commodityName, count,price,"","");
                        goodsAttrDialog.show();
                        goodsAttrDialog.setOnGoodsAttrListener(new GoodsAttrDialog.OnGoodsAttrListener() {

                            @Override
                            public void onAddShoppingCart(String id, String count, String specificationId, String price, String condimentsId,String cartId,String countcart) {
                                addShopCart(id, count, specificationId, price, condimentsId);
                            }

                            @Override
                            public void dissmiss() {

                            }


                        });
                    }else {
//                        if (count.equals("0")) {
//                            deleteByIds(id);
//                        } else {
                            addShopCart(id, count, "", price, condimentsId);
//                        }
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 减到0个删除
     *
     * @param id
     */
    private void deleteByIds(String id) {
        EasyHttp.post(this)
                .api(new DeleteByIdsApi().setIds(id)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode() == 0) {
                    selectMyCart();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private boolean useLoop(List<SelectMyCartBean.ListBean.CartsBean> dataBeanList, String id) {
        for (int i = 0; i < dataBeanList.size(); i++) {
            if (String.valueOf(dataBeanList.get(i).getCommodityId()).equals(id)) {
                return true;
            }
        }
        return false;
    }

    private void addShopCart(String id, String count, String specificationId, String price, String condimentsId) {


        EasyHttp.post(this)
                .api(new AddCartApi().setUserId(SPUtil.get(this, IntentKey.USERID, "")).setCount(count).setCommodityId(id).setMerchantId(merchantid).setSpecificationId(specificationId).setPrice(price).setCondimentsId(condimentsId)).request(new HttpCallback<PublicMsgBean>(this) {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode() == 0) {
                    selectMyCart();
                } else {
                    toast(data.getList());
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rb_diancan:
                rlWeb.setVisibility(View.VISIBLE);
                rlPingjia.setVisibility(View.GONE);

                break;
            case R.id.rb_pingjia:
                rlWeb.setVisibility(View.GONE);
                rlPingjia.setVisibility(View.VISIBLE);

                break;


        }
    }
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode() == EvenConstant.PAYSTAUTS) {
//
            finish();
        }
    }
}
